﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using Caliburn.Micro;
using Wulong.Phone.Qiushi.Models;

namespace Wulong.Phone.Qiushi.ViewModels
{
    public class PicstoryListViewModel : Screen
    {
        private INavigationService _navigationService;
        public PicstoryListViewModel(
            INavigationService navigationService)
        {
            _navigationService = navigationService;
            _picstoryList = new ObservableCollection<QiushiItem>();

            LoadPictures();
        }

        private void LoadPictures()
        {
            IsBusy = true;
            CanViewPicture = false;
            QiushiMapper.GetObservableItems("pic", 10)
                .ObserveOnDispatcher()
                .Finally(() => 
                                { 
                                    IsBusy = false;
                                    CanViewPicture = true;
                                })
                .Subscribe(item => _picstoryList.Add(item),
                           DoAfterException,
                           DoAfterCompleted);
        }


        private bool _isBusy;

        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (_isBusy == value)
                    return;
                _isBusy = value;
                NotifyOfPropertyChange(() => IsBusy);
            }
        }
        private ObservableCollection<QiushiItem> _picstoryList;
        public IEnumerable<QiushiItem> PicstoryList
        {
            get { return _picstoryList; }
            set {}
        }
        private bool _canViewPicture;
        public bool CanViewPicture
        {
            get { return _canViewPicture; }
            set
            {
                if (_canViewPicture == value)
                    return;
                _canViewPicture = value;
                NotifyOfPropertyChange(() => CanViewPicture);
            }
        }

        private QiushiItem _selectedItem;

        public QiushiItem SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (_selectedItem == value)
                    return;
                _selectedItem = value;
                NotifyOfPropertyChange(() => SelectedItem);
            }
        }

        public void ViewPicture(QiushiItem item)
        {
            _navigationService.UriFor<PicViewModel>()
                .WithParam(x=>x.ImageUrl, item.ImageUrl.Replace("small", "large"))
                .Navigate();
        }

        private static void DoAfterException(Exception ex)
        {
            
        }

        private static void DoAfterCompleted()
        {
            
        }
    }
}
